package terminal.gui;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.springframework.scheduling.annotation.Async;

public class ConnectionStatusWindow extends Dialog {

	private static final int MAX_PROGRESS_BAR = 10000;

	private Label lblStatus;
	private ProgressBar progressBar;

	/**
	 * Create the dialog.
	 * 
	 * @param parentShell
	 */
	public ConnectionStatusWindow(Shell parentShell) {
		super(parentShell);
	}

	/**
	 * Create contents of the dialog.
	 * 
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);

		lblStatus = new Label(container, SWT.NONE);
		lblStatus.setText("Awaiting RKW response");
		lblStatus.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));

		progressBar = new ProgressBar(container, SWT.NONE);
		progressBar.setMaximum(MAX_PROGRESS_BAR);
		progressBar.setSelection(MAX_PROGRESS_BAR - 1);
		progressBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

		return container;
	}

	/**
	 * Create contents of the button bar.
	 * 
	 * @param parent
	 */
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
		createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);

		getButton(IDialogConstants.OK_ID).setEnabled(false);
	}

	/**
	 * Return the initial size of the dialog.
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(450, 200);
	}

	public void setConnectionEstablished() {
		Display.getDefault().asyncExec(new Runnable() {
            @Override
            public void run() {
            	progressBar.setSelection(MAX_PROGRESS_BAR);
            	
            	lblStatus.setText("Connection established");
            	getButton(IDialogConstants.OK_ID).setEnabled(true);
            }
        });
	}

	public void setConnectionNotEstablished() {
		Display.getDefault().asyncExec(new Runnable() {
            @Override
            public void run() {
            	progressBar.setSelection(MAX_PROGRESS_BAR);

        		lblStatus.setText("Connection failed");
        		getButton(IDialogConstants.OK_ID).setEnabled(false);
            }
        });
	}
}
